package com.example.xiaomi.Model.Oop;

import com.example.xiaomi.Model.Controller.GodsList;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class Oop {
    //执行js代码
    public String implement_js(String url,String name,Object...arg) throws FileNotFoundException {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        String jsFileName= url;  //js文件所在目录
        FileReader reader = new FileReader(jsFileName);   // 执行指定脚本
        try {
            engine.eval(reader);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
        String c = null;
        if(engine instanceof Invocable) {
            // 调用merge方法，并传入两个参数
            Invocable invoke = (Invocable) engine;
            try {
                //调用了js的add方法
                c = (String) invoke.invokeFunction(name, arg);
            } catch (ScriptException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
        }
        return c;
    }
}
